//
//  HouseholdsViewController.m
//  RONGAO
//
//  Created by Kendama on 2018/2/26.
//  Copyright © 2018年 wei wang. All rights reserved.
//

#import "HouseholdsViewController.h"
#import "DoorListCell.h"
#import "DoorAddViewController.h"
#import "DoorLockViewController.h"


@interface HouseholdsViewController ()<UITableViewDelegate,UITableViewDataSource>

/** UItableView **/
@property(nonatomic,strong) UITableView *tableView;

@property(nonatomic,strong) NSMutableArray *dataSoure;

@end

@implementation HouseholdsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    __weak typeof(self) weakself = self;
    
    self.tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [[DTCloudManager defaultJNI_iOS_SDK] getAllDeviceSuccessCallback:^(NSArray *deviceList) {
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:4];
            for (DTDevice *device in deviceList)
            {
                if ([device.deviceTypeID isEqualToString:TYPEID])
                {
                    [array addObject:device];
                }
            }
            weakself.dataSoure = array;
            [weakself.tableView reloadData];
            [weakself.tableView.mj_header endRefreshing];

        } errorCallback:^(NSDictionary *dic) {
            [weakself.tableView.mj_header endRefreshing];

            NSLog(@"%@",dic);
            
        }];        
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - --------------------------点击事件--------------------------
- (void)onRightButtonClick:(id)sender{
    DoorAddViewController *vc = [[DoorAddViewController alloc] init];
    vc.doorType = HouseholdsDoor;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - --------------------------UITableView dataSource--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSoure.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 56;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}

#pragma mark - --------------------------UITableView delegate--------------------------

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DoorListCell *cell = [DoorListCell dequeueReusableWithTableView:tableView];
    cell.deviceNameLabel.text = @"智能门锁";
    DTDevice *info = self.dataSoure[indexPath.row];

    cell.deviceNameLabel.text = info.deviceName;
    if (info.isOnline == YES) {

        cell.stautsBtn.selected = YES;

    }else{

        cell.stautsBtn.selected = NO;

    }
    
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DTDevice *info = self.dataSoure[indexPath.row];
    SAVE_OBJECT(info.macAddress, DeviceMac);
    DoorLockViewController *vc = [DoorLockViewController new];
    vc.deviceMac = info.macAddress;
    [self.navigationController pushViewController:vc animated:YES];
}
                 
                 


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
 
 return YES;
}

#pragma mark 在滑动手势删除某一行的时候，显示出更多的按钮
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    // 添加一个删除按钮
    DTDevice *info = self.dataSoure[indexPath.row];
    
    __weak typeof(self) weakself = self;
    UITableViewRowAction *moreRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"重命名" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"更改用户名");
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"重命名" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        
        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
            textField.placeholder = @"请输入设备名";
        }];
        __weak typeof(alertController) alere = alertController;
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        __weak typeof(self) weakself = self;
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSString *deviceName = alere.textFields.firstObject.text;

            
            if (![NSString isContainsTwoEmoji:deviceName] && [deviceName length] <=8 ){
                if ([alere.textFields.firstObject.text length]<=0){
                    
                    return [SVProgressHUD showErrorWithStatus:@"设备名称不能为空"];
                }
                NSString *deviceName = alere.textFields.firstObject.text;
                
                [[DTCloudManager defaultJNI_iOS_SDK] renameDeviceByUUID:info.deviceUUID andDeviceName:deviceName successCallback:^(NSDictionary *dic) {

                    if ([dic[@"errcode"] integerValue] == 0) {

                        info.deviceName = deviceName;
                        [weakself.tableView reloadData];

                    }else{

                        [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];

                    }

                } errorCallback:^(NSDictionary *dic) {
                    [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];

                }];

            }else{
                
                [SVProgressHUD showErrorWithStatus:@"输入名称过长或输入了非法字符"];
                
            }
            
        }];
        
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
        
    }];
    
    
    UITableViewRowAction *deletRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        [[AlertViewManager shareManager] initWithMessage:@"是否删除设备" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
            if (buttonIndex == 1) {
                [[DTCloudManager defaultJNI_iOS_SDK] unBindDeviceByUUID:info.deviceUUID successCallback:^(NSDictionary *dic) {
                    [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                    [weakself.dataSoure removeObject:info];
                    [weakself.tableView reloadData];
                    
                } errorCallback:^(NSDictionary *dic) {
                    
                    [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
                }];
            }
        }];
    }];
    
    moreRowAction.backgroundColor  = [UIColor colorWithHexString:@"646464"];
    deletRowAction.backgroundColor = [UIColor colorWithHexString:@"f8533d"];
    
    return @[deletRowAction,moreRowAction];
}

#pragma mark - --------------------------懒加载--------------------------
- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        //        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
        //        _tableView.scrollEnabled = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}
                 
- (NSMutableArray *)dataSoure{
 
 if (!_dataSoure) {
     _dataSoure = [NSMutableArray array];
 }
 return _dataSoure;
}

#pragma mark - --------------------------约束--------------------------
- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(superView);
    }];
}
                 
#pragma mark - --------------------------导航栏--------------------------
- (void)setNavigationStyle
{
     [self setRightButtonImage:[UIImage imageNamed:@"icon_add_nor"]];
     [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
     [self setNavigationTitle:@"设备列表" titleColor:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
